package com.srong.nio.react;

import com.sorng.nio.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Executor;

@Slf4j
public class JavaService {
    private static final Executor executor = Runnable::run;

    public static void main(String[] args) throws IOException {

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        Selector serviceSelect = Selector.open();

        bindSelector(socketChannel, serviceSelect);

        while(!Thread.interrupted()) {

            serviceSelect.select(1000);
            Set<SelectionKey> selectionKeys = serviceSelect.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                final SelectionKey next = iterator.next();

                if (!next.isValid()) {
                    continue;
                }

                if (next.isAcceptable()) {
                    handelAccept( next);
                }
                if (next.isWritable()) {

                }

                if (next.isReadable()) {

                }

                if (next.isConnectable()) {

                }

            }
        }




    }

    private static void handelAccept( SelectionKey next) throws IOException {
        Selector selector = next.selector();
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) next.channel();
        SocketChannel channel = serverSocketChannel.accept();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    private static void bindSelector(ServerSocketChannel socketChannel, Selector serviceSelect) throws IOException {
        Properties properties = PropertiesUtil.getProperties(
                JavaService.class,
                "conf.properties"
        );
        socketChannel.configureBlocking(false);

        InetSocketAddress address = new InetSocketAddress(
                Integer.parseInt(properties.getProperty("remote.port"))
        );
        socketChannel.bind(address);
        socketChannel.register(serviceSelect, SelectionKey.OP_ACCEPT);
    }
}
